<template>
  <div class="modal-overlay" @click.self="closeMainModal">
    <div class="modal-content">
      <div class="modal-header">
        <h3>{{ isEditMode ? '编辑排班' : '添加排班' }}</h3>
        <button class="close-btn" @click="closeMainModal">&times;</button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label for="schedule-name">班次名称:</label>
            <input id="schedule-name" type="text" v-model="formData.shiftName" required>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label for="schedule-date">排班日期:</label>
              <input id="schedule-date" type="date" v-model="formData.date" required>
            </div>
            <div class="form-group">
              <label for="start-time">开始时间:</label>
              <input id="start-time" type="time" v-model="formData.startTime" required>
            </div>
            <div class="form-group">
              <label for="end-time">结束时间:</label>
              <input id="end-time" type="time" v-model="formData.endTime" required>
            </div>
          </div>
          <div class="form-group">
            <label for="schedule-personnel">排班人员 (点击选择警员):</label>
            <textarea id="schedule-personnel" readonly @click="isOfficerModalOpen = true" :value="displaySelectedOfficers" rows="3" placeholder="点击选择警员"></textarea>
          </div>
          <div class="form-group">
            <label for="schedule-location">地点/区域:</label>
            <select id="schedule-location" v-model="formData.location">
              <option disabled value="">请选择地点/区域</option>
              <option>乌尔禾区巡逻区域</option>
              <option>白碱滩区巡逻区域</option>
              <option>独山子石化基地巡逻区域</option>
              <option>世纪公园巡逻区域</option>
            </select>
          </div>
          <div class="form-group">
            <label for="schedule-description">任务描述 (选填):</label>
            <textarea id="schedule-description" v-model="formData.taskDescription" rows="3"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button class="btn btn-cancel" @click="closeMainModal">取消</button>
        <button class="btn btn-confirm" @click="submitForm">{{ isEditMode ? '更新' : '提交' }}</button>
      </div>
    </div>

    <OfficerSelectionModal
      v-if="isOfficerModalOpen"
      :police-list="policeList"
      :initial-selection="formData.officers"
      @close="isOfficerModalOpen = false"
      @confirm="updateSelectedOfficers"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import OfficerSelectionModal from './OfficerSelectionModal.vue';

const props = defineProps<{
  isEditMode: boolean,
  initialData?: any,
  policeList: any[]
}>();
const emit = defineEmits(['close', 'save']);

const isOfficerModalOpen = ref(false);

const getDefaultFormData = () => ({
  shiftId: props.isEditMode ? props.initialData?.shiftId : undefined,
  shiftName: '',
  date: '',
  startTime: '',
  endTime: '',
  officers: [],
  location: '',
  taskDescription: ''
});

const formData = reactive(getDefaultFormData());

watch(() => props.initialData, (newData) => {
  if (newData) {
    // 处理时间格式
    if (newData.timeRange) {
      const [startTime, endTime] = newData.timeRange.split('-');
      newData.startTime = startTime;
      newData.endTime = endTime;
    }
    Object.assign(formData, { ...getDefaultFormData(), ...newData });
  } else {
    Object.assign(formData, getDefaultFormData());
  }
}, { immediate: true });

const displaySelectedOfficers = computed(() => {
  if (!formData.officers || formData.officers.length === 0) return '';
  return formData.officers.map((p: any) => p.officerName || p.name).join('、');
});

const updateSelectedOfficers = (selected: any[]) => {
  formData.officers = selected;
  isOfficerModalOpen.value = false;
};

const closeMainModal = () => { emit('close'); };

const submitForm = () => {
  if (!formData.shiftName || !formData.date || !formData.startTime || !formData.endTime) {
    alert('请填写所有必填项！');
    return;
  }

  // 合并开始时间和结束时间为时间段
  formData.timeRange = `${formData.startTime}-${formData.endTime}`;

  // 只将最终的表单数据 emit 出去
  const dataToSave = {
    ...formData,
    officer: formData.officers.map(o => ({ officerId: o.officerId || o.id }))
  };
  emit('save', dataToSave);
};
</script>

<style scoped>
/* 样式保持不变 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  width: 600px;
  max-width: 95%;
  color: #333;
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
}
.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}
.close-btn {
  background: none;
  border: none;
  font-size: 2rem;
  line-height: 1;
  cursor: pointer;
  color: #6c757d;
}
.modal-body {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}
.form-group {
  margin-bottom: 20px;
}
.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
}
.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 10px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.2s;
  font-family: inherit;
}
textarea[readonly] {
  background-color: #f8f9fa;
  cursor: pointer;
}
.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid #e9ecef;
  gap: 10px;
}
.btn {
  padding: 10px 20px;
  border-radius: 6px;
  border: none;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}
.btn-cancel {
  background-color: #6c757d;
  color: white;
}
.btn-confirm {
  background-color: #198754;
  color: white;
}
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #6c757d;
}
</style>
